package org.ediba.siri.core.user.data;

import java.util.Collection;
import java.util.Map;

import org.ediba.siri.core.Filter;
import org.ediba.siri.core.common.data.HibernateDomainDao;
import org.ediba.siri.core.user.domain.UserGroup;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;

public class HibernateUserGroupDao extends HibernateDomainDao<UserGroup, Integer> implements UserGroupDao {

	public HibernateUserGroupDao() {super(UserGroup.class);}
	
	@Override
	protected DetachedCriteria buildCriteria(Map<Filter, Collection<Object>> filters) {
		DetachedCriteria detachedCriteria = this.buildCriteria();
		Disjunction or;
		Conjunction and = Restrictions.conjunction();
		
		if (filters.containsKey(Filter.USER))
			detachedCriteria.createAlias(Filter.USER.getCollection(), Filter.USER.getProperty());
		
		for (Map.Entry<Filter,Collection<Object>> filter : filters.entrySet()){
			or = Restrictions.disjunction();
			for (Object value : filter.getValue())
				switch (filter.getKey()) {
					case ID: or.add(Restrictions.idEq((Integer)value));
					break;
					case USER: or.add(Restrictions.eq(Filter.USER.getPropertyId(), (Integer)value));
					break;
				}
			and.add(or);
		}
		
		detachedCriteria.add(and);
		return detachedCriteria;
	}

}
